#
#  TarjanDocument.py
#  tarjan
#
#  Created by Anders Hellerup Madsen on 4/30/08.
#  Copyright __MyCompanyName__ 2008. All rights reserved.
#

from Foundation import *
from AppKit import *
import pickle
from map import Map
from tarjanTextContainer import *

class TarjanDocument(NSDocument):

    mapView = objc.IBOutlet()
    textView = objc.IBOutlet()

    def init(self):
        self = super(TarjanDocument, self).init()

        # initialization code
        self.map = Map()
        self.text = NSAttributedString.alloc().init()

        return self

    # KVC compliance
    def get_map(self): return self.map
    def set_map(self, value): self.map = value
        
    def windowNibName(self):
        return u"TarjanDocument"
    
    def windowControllerDidLoadNib_(self, aController):
        super(TarjanDocument, self).windowControllerDidLoadNib_(aController)
        self.mapView.registerEventListeners()
        self.mapView.resize()

        # replace textcontainer for textview
        layout_manager = self.textView.layoutManager()
        text_container = tarjanTextContainer.alloc().init()
        text_container.setWidthTracksTextView_(YES)
        text_container.setHeightTracksTextView_(YES)

        while len(layout_manager.textContainers()):
            layout_manager.removeTextContainerAtIndex_(0)

        layout_manager.addTextContainer_(text_container)
        self.textView.replaceTextContainer_(text_container)

        # if restore from file, set content of textView to self.text
        self.textView.textStorage().setAttributedString_(self.text)

    def dataOfType_error_(self, typeName, outError):

        data = NSMutableData.data()
        mapdata = NSString.stringWithString_(pickle.dumps(self.mapView.map))

        archiver = NSKeyedArchiver.alloc().initForWritingWithMutableData_(data)
        archiver.encodeObject_forKey_(mapdata, 'map')
        archiver.encodeObject_forKey_(self.textView.textStorage(), 'text')
        archiver.finishEncoding()

        return (data, None) # tuple because of **NSError rule
    
    def readFromData_ofType_error_(self, data, typeName, outError):
        unarchiver = NSKeyedUnarchiver.alloc().initForReadingWithData_(data)
        self.text = unarchiver.decodeObjectForKey_('text')
        self.map = pickle.loads(unarchiver.decodeObjectForKey_('map'))
        unarchiver.finishDecoding()

        return (True, None) # tuple because of **NSError rule



